package com.jjwxc.jwjskandriod.fragment

import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.text.TextUtils
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.alibaba.fastjson.JSON
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.android.material.tabs.TabLayout.TabLayoutOnPageChangeListener
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jjwxc.jwjskandriod.R
import com.jjwxc.jwjskandriod.activity.FindActivity
import com.jjwxc.jwjskandriod.adapter.MainSuggestAdapter
import com.jjwxc.jwjskandriod.config.Constants
import com.jjwxc.jwjskandriod.databinding.FragmentNewSuggestMainBinding
import com.jjwxc.jwjskandriod.framework.utils.PreUtils
import com.jjwxc.jwjskandriod.model.LoginResponse
import com.jjwxc.jwjskandriod.my.data.UserInfoBg
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant
import com.umeng.analytics.MobclickAgent

/**
 * 新版推荐主视图类
 */
class MainSuggestFragment : Fragment() {
    private lateinit var dataBinding: FragmentNewSuggestMainBinding
    private var listBean: ArrayList<LoginResponse.DataBean.BookCenterTabBean> = ArrayList()

    private var adapter: MainSuggestAdapter? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        dataBinding = FragmentNewSuggestMainBinding.inflate(inflater, container, false)

        initData()
        initListener()
        return dataBinding.root
    }

    /**
     * 初始化數據
     */
    private fun initData() {
        initTabLayout()
        initPager()
        initCurrentFragment()
    }

    private fun initListener() {
        // 查找
        dataBinding.imgFind.setOnClickListener {
            val intent = Intent(activity, FindActivity::class.java)
            startActivity(intent)
        }
    }

    /**
     * 设置当前展示项
     */
    private fun initCurrentFragment() {
        val string = PreUtils.getString(Constants.TAB_ITEM_SUGGEST_TO_TYPES, "")

        if (!TextUtils.isEmpty(string)) {
            val toTab = JSON.parseObject(string, LoginResponse.DataBean.BookCenterTabBean::class.java)
            if (toTab == null || listBean == null || listBean.isEmpty()) return;

            // 如果不是首次启动，不跳转到其他页面
//            if (!isFirstLaunch()) return;

            listBean.forEach{
                // 如果后端有提供跳转项，则跳转到指定位置
                if (it.tabId == toTab.tabId) {
                    val index = listBean.indexOf(it)
                    dataBinding.viewSuggestPager.currentItem = index
                }
            }
        }
    }

    /**
     * 設置頁卡顯示效果
     *
     * @param tabLayout
     * @param inflater
     * @param tabBean
     */
    private fun setTab(tabLayout: TabLayout, inflater: LayoutInflater, tabBean: LoginResponse.DataBean.BookCenterTabBean) {
        val tab = tabLayout.newTab()
        val view: View = inflater.inflate(R.layout.suggest_item_fragment, null)
        // 使用自定義視圖，目的是為了便於修改，也可使用自帶的視圖
        tab.customView = view
        val tvTitle = view.findViewById<View>(R.id.txt_suggest_tab) as TextView
        tvTitle.text = tabBean.name

        tabLayout.addTab(tab)
    }

    /**
     * 初始化 TabLayout
     */
    private fun initTabLayout() {
        val string = PreUtils.getString(Constants.TAB_ITEM_SUGGEST_TYPES, "")

        if (!TextUtils.isEmpty(string)) {
            listBean.clear()

            val list = JSON.parseArray(string, LoginResponse.DataBean.BookCenterTabBean::class.java)
            list.forEach{
                listBean.add(it)
                setTab(dataBinding.tabSuggestLayout, LayoutInflater.from(context), it)
            }
        }
    }

    /**
     * 初始化 ViewPager
     */
    private fun initPager() {
        adapter = MainSuggestAdapter(childFragmentManager)
        adapter?.setList(listBean)
        dataBinding.viewSuggestPager.offscreenPageLimit = dataBinding.tabSuggestLayout.tabCount
        dataBinding.viewSuggestPager.adapter = adapter
        val linearLayout = dataBinding.tabSuggestLayout.getTabAt(0)?.customView as LinearLayout
        val textView = linearLayout.getChildAt(0) as TextView
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22f)
        textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
        // 關聯切換
        dataBinding.viewSuggestPager.addOnPageChangeListener(TabLayoutOnPageChangeListener(dataBinding.tabSuggestLayout))
        dataBinding.tabSuggestLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                // 取消平滑切換
                dataBinding.viewSuggestPager.setCurrentItem(tab.position, false)
                val s: Int = dataBinding.tabSuggestLayout.tabCount
                for (i in 0 until s) {
                    if (tab.position == i) {
                        val linearLayout = dataBinding.tabSuggestLayout.getTabAt(i)?.customView as LinearLayout
                        val textView = linearLayout.getChildAt(0) as TextView
                        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22f)
                        textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                    } else {
                        val linearLayout = dataBinding.tabSuggestLayout.getTabAt(i)?.customView as LinearLayout
                        val textView = linearLayout.getChildAt(0) as TextView
                        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22f)
                        textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                    }
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {}
            override fun onTabReselected(tab: TabLayout.Tab) {}
        })
    }

    override fun onResume() {
        super.onResume()
        LiveEventBus.get(Constants.Background, Int::class.java).observe(
            this
        ) { integer: Int ->
            if (integer < UserInfoBg.BACKGROUND_RID.size) {
                dataBinding.llBgVip.setBackgroundResource(UserInfoBg.BACKGROUND_RID[integer])
            } else {
                dataBinding.llBgVip.setBackgroundResource(R.color.white)
            }
        }

        MobclickAgent.onEvent(context, UMConstant.SUGGEST_TUIJIAN)
    }

    /**
     * 判断用户是否是今天首次启动
     */
    /*private fun isFirstLaunch(): Boolean {
        val emailToTab: MutableMap<String, String> = (PreUtils.getMap(Constants.EMAIL_TAB) ?: HashMap<String, String>()) as MutableMap<String, String>

        // 获取当前日期
        val calendar = Calendar.getInstance()
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val currentDate = dateFormat.format(calendar.time)

        val email = PreUtils.getString(Constants.EMAIL, null)
        if (TextUtils.isEmpty(email)) return false

        // 判断Email是否存在，存在取出上次启动日期；否侧首次启动
        val lastLaunchDate = if (emailToTab.contains(email)) {
            emailToTab[email] ?: currentDate
        } else {
            0
        }

        // 判断用户是否是每天首次启动
        return if (currentDate != lastLaunchDate) {
            emailToTab[email] = currentDate
            PreUtils.setMapString(Constants.EMAIL_TAB, emailToTab)
            true
        } else {
            false
        }
    }*/
}